/***********************************************************
* 
*     File Name:  test.cpp
* 
*        Author:  Algolc
* 
*          mail:  17360224@qq.com
* 
*  Created Time:  Mon 06 Aug 2018 02:12:12 PM CST
* 
***********************************************************/

#include <stdlib.h>
#include <iostream>
#include <fstream>
#include "test.pb.h"
#include <google/protobuf/util/json_util.h>

using namespace std;

std::string SerializeJsonString(const SearchRequest& test) {
    std::string tmp_string="";

    google::protobuf::util::JsonPrintOptions options;
    options.add_whitespace = true;
    options.always_print_primitive_fields = true;
    //options.preserve_proto_field_names = true;
    
    MessageToJsonString(test, &tmp_string, options);
    return tmp_string;
}

void ParseJsonString(SearchRequest& test) {
    ifstream in("config.json");
    if (!in.is_open()) {
        cout << "error open status" << endl;
    }
        
    std::string buffer((std::istreambuf_iterator<char>(in)),
                         std::istreambuf_iterator<char>());

    std::string tmp_string = buffer;
    google::protobuf::util::JsonParseOptions options2;
    JsonStringToMessage(buffer, &test, options2);
    
    cout << test.DebugString() << endl;
}

int main() {
    SearchRequest test;

#if 0
    test.set_query("fuck you");
    test.set_page_number(11);
    test.set_result_per_page(18);

    test.add_number(1000);
    test.add_number(1001);
    test.add_number(1002);
    test.add_number(1003);

    for (int i = 0; i < 4; ++i) {
        RepeatedNumber* repNum = test.add_numbers();
        if (!repNum) {
            printf("error num\n");
            return -1;
        }

        repNum->set_name("张煜"); 
        repNum->set_age(19+i);
        repNum->set_marryed(i%1);
        repNum->set_house_number(5+i);
    }

    //cout  << "debug" << test.DebugString() << endl;
    auto JsonString = SerializeJsonString(test);
    
    if(JsonString.empty()) {
        printf("serialize to Json error");
        return -3;
    }

    cout << "\n\n" << JsonString << endl;
#endif

    ParseJsonString(test);
    return 0;
}
